package com.check.operation.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.check.operation.CheckApplication;
import com.check.operation.R;
import com.check.operation.base.BaseFragment;
import com.check.operation.model.Inpatient;
import com.check.operation.model.MessagRe;
import com.check.operation.model.Message;
import com.check.operation.model.Operation;
import com.check.operation.model.RequestUse;
import com.check.operation.service.ShAdapter;
import com.check.operation.view.MainActivity_;
import com.szj.util.HttpUtil;
import com.szj.util.JSONUtil;
import com.szj.util.SysUtil;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.App;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 术后申请
 */
@EFragment(R.layout.fragment_sh)
public class ShFragment extends BaseFragment implements AdapterView.OnItemClickListener {

    public String action;
    public static final String TAG="INSH";
    public static final Integer CHECK_CODE = 110;
    public static final Integer CHECK_RESULT_CODE = 100;
    public static final String ACTION = "com.rmyy.sshc.specimen";

    @App CheckApplication checkApp;
    @ViewById TextView smh;
    @ViewById ListView sqlb;
    @ViewById TextView  zyh;
    @ViewById TextView xm;
    @ViewById TextView xb;
    @ViewById TextView ks;

    String tmsmh;
    final String sszt="f";
    final String ssztmc="术后";

    ShAdapter shAdapter;

    List<Operation> operations;

    private BroadcastReceiver receiver;

    Context mContext;

    @AfterViews
    public void initview(){
        shAdapter = new ShAdapter(getLayoutInflater(), checkApp.getSfdgdic(), checkApp.getUserRe().getUser());
        mContext = getActivity();
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if(ACTION.equals(intent.getAction())) {
                    Bundle bundel = intent.getBundleExtra("data");
                    Intent intent1 = new Intent(mContext, MainActivity_.class);
                    intent1.putExtra("data", bundel);
                    startActivityForResult(intent1, CHECK_CODE);
                }
            }
        };
    }

    @Background
    public void refdownsj(final String zyh){
        initdata(zyh);
        String action = "patient/patientinfo";
        Map<String,Object> params = checkApp.getParams();

        params.put("user",checkApp.getUserRe().getUser());
        params.put("request", new Object(){
            public String barCode = zyh;
        });
        String rs= HttpUtil.postJSON(action, JSONObject.toJSONString(params));
        if(SysUtil.isNotNUll(rs)){
            if(rs.indexOf("message") <= 0){
                Message message = (Message) JSONUtil.fromJson(rs, Message.class);
                alert(message);
            }else{
                MessagRe<Inpatient> inp = JSONObject.parseObject(rs, new TypeReference<MessagRe<Inpatient>>(){});
                operations = inp.value.operations;
                uiInpat(inp);
                uiOpre(operations);
            }
        }
        sqlb.setOnItemClickListener(this);

    }

    @UiThread
    public void initdata(String tmh){
        shAdapter.setCws(new ArrayList<Operation>());
        shAdapter.notifyDataSetInvalidated();
        smh.setText(tmh);
        zyh.setText(null);
        xm.setText(null);
        xb.setText(null);
        ks.setText(null);
    }

    @UiThread
    public void uiInpat(MessagRe<Inpatient> inp){
        Inpatient inpatient = inp.value;
        shAdapter.setZyh(inpatient.inpatient_no);
        zyh.setText(inpatient.inpatient_no);
        xm.setText(inpatient.name);
        xb.setText(inpatient.sexname);
        ks.setText(inpatient.dept_name);
    }

    @UiThread
    public void uiOpre(List<Operation> operations){
        for(Operation op:operations){
            op.op_position_name = checkApp.getDics().get("1021").get(op.op_position);
            op.process_status_name = checkApp.getDics().get("1020").get(op.process_status);
        }
        shAdapter.setCws(operations);
        sqlb.setAdapter(shAdapter);
        shAdapter.notifyDataSetChanged();
    }

    @UiThread
    public void alert(Message message){
        Toast.makeText(getActivity(), message.text,  Toast.LENGTH_SHORT).show();
    }

    @UiThread
    public void alert(String message){
        Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onGetBarValue(String paramString) {
        refdownsj(paramString);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        final Operation operation = operations.get(position);
    }

    @Override
    public void onResume() {
        super.onResume();
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.rmyy.sshc.specimen");
        getActivity().registerReceiver(receiver, filter);
    }

    @Override
    public void onPause() {
        super.onPause();
        getActivity().unregisterReceiver(receiver);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        try {
            super.onActivityResult(requestCode, resultCode, data);
            if(CHECK_CODE == requestCode && CHECK_RESULT_CODE == resultCode) {
                Bundle bundle = data.getBundleExtra("data");
                if(bundle != null && bundle.getBoolean("checked")) {
                    String action = bundle.getString("action");
                    RequestUse requestUse = new RequestUse();
                    requestUse.user = checkApp.getUserRe().getUser();
                    Map<String, Object> params = new HashMap<String, Object>();
                    params.put("surgicNo", bundle.getString("surgicNo"));
                    params.put("processType", bundle.getString("processType"));
                    params.put("position", bundle.getString("position"));
                    params.put("room", bundle.getString("room"));
                    params.put("specimen", 1);
                    requestUse.request = params;
                    String rs = HttpUtil.postJSON(action, JSONObject.toJSONString(requestUse));
                    MessagRe<Inpatient> mereturn = JSONObject.parseObject(rs, new TypeReference<MessagRe<Inpatient>>() {
                    });
                    Toast.makeText(getActivity(), mereturn.message.text, Toast.LENGTH_SHORT).show();
                    int index = bundle.getInt("index");
                    View v = sqlb.getChildAt(index);
                    ShAdapter.ViewHolder holder = (ShAdapter.ViewHolder) v.getTag();
                    if ("success".equals(mereturn.message.code)) {
                        holder.success(getActivity());
                    } else {
                        holder.fail(getActivity());
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
}
